﻿#! -*- coding:utf-8 -*-

'''
This is used to monitor Windchill system status
'''

__author__="zhaoxp"

import os
import os.path
import re
import time
import sys
import smtplib
import commands
import smtplib

'''
methodServerCount=0
smtpServer="smtpinternal.lenovo.com"
mailSender="wtmonitor_python@lenovo.com"
mailReceivers=["zhaoxp2@lenovo.com","liuxt2@lenovo.com","zhangll9@lenovo.com"]
wtHome="www"
'''

class WTMonitor(object):
	def __init__(self):
		self.methodServerCount=0
		self.smtpServer="smtpinternal.lenovo.com"
		self.mailSender="wtmonitor_python@lenovo.com"
		self.mailReceivers=["zhaoxp2@lenovo.com","liuxt2@lenovo.com","zhangll9@lenovo.com"]
		self.wtHome=""
		self.errors={}
	def readProperties(self):
		assert self.wtHome!="","WT_HOME should not be empty"+self.wtHome
		wtFilePath=os.path.join(self.wtHome,'codebase','wt.properties')
		print "",wtFilePath
		#wt.manager.monitor.start.MethodServer=4
		#wt.manager.monitor.services=BackgroundMethodServer BackgroundMethodServer1 BackgroundMethodServer2 BackgroundMethodServer3 BackgroundMethodServer4 BackgroundMethodServer5
		#wt.mail.mailhost=smtpinternal.lenovo.com
		msCountPrefix="wt.manager.monitor.start.MethodServer="
		servicePrefix="wt.manager.monitor.services="
		smtpServerPrefix="wt.mail.mailhost="
		for line in open(wtFilePath):
			line=line[0:len(line)-1]
			if line[:len(msCountPrefix)]==msCountPrefix :
				self.methodServerCount=self.methodServerCount+int(line[len(msCountPrefix):])
			if line[:len(servicePrefix)]==servicePrefix :
				c=0
				for tmp in line[len(servicePrefix):].split(" "):
					if re.match("^BackgroundMethodServer",tmp):
						c=c+1
				self.methodServerCount=self.methodServerCount+c
			if line[:len(smtpServerPrefix)]==smtpServerPrefix and len(line)>len(smtpServerPrefix):
				self.smtpServer=line[len(smtpServerPrefix):]
		#print "methodServerCount=",methodServerCount
		#print "smtpServer=",smtpServer
		pass
	def autoHandleDir(self,ptcHomePath):
		print("ptcHomePath:"+ptcHomePath)
		dirnames=os.listdir(ptcHomePath)
		ver=0
		vername=""
		for dname in dirnames:
			if os.path.isdir(os.path.join(ptcHomePath,dname)) and re.match("^Windchill_[0-9]{1,2}\\.[0-9]$",dname):
				tmp=float(dname[10:])
				if tmp>ver:
					ver=tmp
					vername=dname
		self.wtHome=os.path.join(ptcHomePath,vername,'Windchill')
	def handleArgs(self,argv):
		i=0
		while i<len(argv):
			if argv[i].lower()=="-h":
				printHelpInfo()
			if argv[i].lower()=="-m" and (i+1)<len(argv) and argv[i+1][0]!='-':
				self.smtpServer=argv[i+1]
				i=i+1
			if argv[i].lower()=="-s" and (i+1)<len(argv) and argv[i+1][0]!='-':
				self.mailSender=argv[i+1]
				i=i+1
			if argv[i].lower()=="-r" and (i+1)<len(argv) and argv[i+1][0]!='-':
				self.mailReceivers=argv[i+1].split(",")
				i=i+1
			if argv[i].lower()=="-c" and (i+1)<len(argv) and argv[i+1][0]!='-':
				self.methodServerCount=int(argv[i+1])
				i=i+1
			if argv[i].lower()=="-w" and (i+1)<len(argv) and argv[i+1][0]!='-':
				self.wtHome=argv[i+1]
				i=i+1
			i=i+1
	
	def monitorWTProcess(self):
		status,result=commands.getstatusoutput("ps -ef|grep -v grep|egrep '(wt.method.MethodServerMain|wt.manager.ServerManagerMain)'|wc -l")
		assert status==0,"Command running error, exit status:"+status
		if int(result)!=(self.methodServerCount+1):
			self.errors["MS_count"]="ServerManager and MethodServer count error:"+result
			return
	def mailErrors(self):
		#self.errors['hello']='world'
		if len(self.errors)>0:
			try:
				msg=""
				for k in self.errors:
					msg=msg+self.errors[k]+"\r\n"
				mailTitle="Windchill monitor result"
				content="From: "+self.mailSender+"\r\nTo:"+';'.join(self.mailReceivers)+"\r\nSubject:"+mailTitle+"\r\n\r\n"+msg+"\r\n"
				smtpObj=smtplib.SMTP(self.smtpServer)
				smtpObj.sendmail(self.mailSender,';'.join(self.mailReceivers),content)
				smtpObj.close()				
			except smtplib.SMTPException ,ex:
				print "error when sending email:"
				print ex
	def GetWTHome(self):
		return self.wtHome
	def printProperties(self):
		print "----------All Properties----------"
		print "methodServerCount =",self.methodServerCount
		print "smtpServer        =",self.smtpServer
		print "mailSender        =",self.mailSender
		print "mailReceivers     =",self.mailReceivers
		print "wtHome            =",self.wtHome
		print "----------End Properties----------"

def autoHandleDir(ptcHomePath):
	print("ptcHomePath:"+ptcHomePath)
	dirnames=os.listdir(ptcHomePath)
	ver=0
	vername=""
	for dname in dirnames:
		if os.path.isdir(os.path.join(ptcHomePath,dname)) and re.match("^Windchill_[0-9]{1,2}\\.[0-9]$",dname):
			tmp=float(dname[10:])
			if tmp>ver:
				ver=tmp
				vername=dname
	wtFilePath=os.path.join(ptcHomePath,vername,'Windchill','codebase','wt.properties')
	return os.path.join(ptcHomePath,vername,'Windchill')

def autoHandle(home):
	wtFilePath=os.path.join(home,'codebase','wt.properties')
	#wt.manager.monitor.start.MethodServer=4
	#wt.manager.monitor.services=BackgroundMethodServer BackgroundMethodServer1 BackgroundMethodServer2 BackgroundMethodServer3 BackgroundMethodServer4 BackgroundMethodServer5
	#wt.mail.mailhost=smtpinternal.lenovo.com
	msCountPrefix="wt.manager.monitor.start.MethodServer="
	servicePrefix="wt.manager.monitor.services="
	smtpServerPrefix="wt.mail.mailhost="
	for line in open(wtFilePath):
		if line[:len(msCountPrefix)]==msCountPrefix :
			methodServerCount=int(line[len(msCountPrefix):])+1
		if line[:len(servicePrefix)]==servicePrefix :
			c=0
			for tmp in line[len(servicePrefix):].split(" "):
				if re.match("^BackgroundMethodServer",tmp):
					c=c+1
			methodServerCount=methodServerCount+c
		if line[:len(smtpServerPrefix)]==smtpServerPrefix:
			smtpServer=line[len(smtpServerPrefix):]
	#print "methodServerCount=",methodServerCount
	#print "smtpServer=",smtpServer

def printHelpInfo():
	print '''
This tool is used to monitor Windchill system.
args:
  -m smtp server address
  -s mail sender address
  -r mail receiver addresses seperated by comma(,)
  -c method server count (inlcuding background methodserver)
  -w windchill home which equas WT_HOME in Windchill environment variables
  -h help information
'''
	
def handleArgs():
	print 'handleArgs',sys.argv
	argv=sys.argv
	i=0
	while i<len(argv):
		print argv[i]
		if argv[i].lower()=="-h":
			printHelpInfo()
		if argv[i].lower()=="-m" and (i+1)<len(argv) and argv[i+1][0]!='-':
			smtpServer=argv[i+1]
			i=i+1
		if argv[i].lower()=="-s" and (i+1)<len(argv) and argv[i+1][0]!='-':
			mailSender=argv[i+1]
			i=i+1
		if argv[i].lower()=="-r" and (i+1)<len(argv) and argv[i+1][0]!='-':
			mailReceivers=argv[i+1].split(",")
			i=i+1
		if argv[i].lower()=="-c" and (i+1)<len(argv) and argv[i+1][0]!='-':
			methodServerCount=int(argv[i+1])
			i=i+1
		if argv[i].lower()=="-w" and (i+1)<len(argv) and argv[i+1][0]!='-':
			wtHome=argv[i+1]
			i=i+1
			print '-------------',wtHome
		i=i+1
	pass

if __name__=='__main__':
	'''
	print("Windchill system monitor tool")
	ptcHomePath="/apphome/ptc"
	ptcHomePath="D:\\temp"
	h=autoHandleDir(ptcHomePath)
	print "h=",h
	print "wtHome=",wtHome
	handleArgs()
	print "wtHome=",wtHome
	print "methodserverCount=",methodserverCount
	'''
	ptcHomePath="/apphome/ptc"
	#ptcHomePath="D:\\temp"
	m=WTMonitor()
	m.printProperties()
	m.autoHandleDir(ptcHomePath)
	m.handleArgs(sys.argv)
	#print "GetWTHome=",m.GetWTHome()
	m.printProperties()
	m.readProperties()
	m.printProperties()
	m.monitorWTProcess()
	m.mailErrors()
	
	